#include "UsrAI.h"
#include <set>
#include <iostream>
#include <unordered_map>
#include <cmath>
#include <fstream>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
// 任务管理结构体（记录单位与目标资源的绑定关系）
struct Task {
    int unitSN;         // 执行任务的单位SN
    int targetSN;       // 目标资源SN（渔场）
    bool isActive;      // 任务是否有效（资源未耗尽）
};

// 渔场信息结构体（用于排序和管理）
struct FishingSpot {
    int sn;             // 渔场SN
    double distance;    // 到市镇中心的距离
    int remaining;      // 剩余资源量
};

// 全局任务与状态变量（静态变量保持生命周期）
static vector<Task> fishingTasks;      // 村民渔场采集任务列表
static vector<Task> boatTasks;         // 渔船捕鱼任务列表
static bool dockBuilt = false;         // 船坞是否已建造
static int fishingBoatCount = 0;       // 当前渔船数量
// 计算两点之间的距离
double calDistance(double DR1, double UR1, double DR2, double UR2) {
    return sqrt(pow(DR1 - DR2, 2) + pow(UR1 - UR2, 2));
}

// 建立地图的函数
void buildMap(tagInfo& info, char map[128][128]) {
    // 初始化地图数组，将陆地设为高度 + '0'，海洋设为 '-'
    for (int i = 0; i < 128; ++i) {
        for (int j = 0; j < 128; ++j) {
            if (info.theMap[i][j] > 0) {
                map[i][j] = '0' + static_cast<char>((*info.theMap)[i][j].height);
            } else {
                map[i][j] = '-';
            }
        }
    }

    // 遍历资源，将其块坐标标记为资源类型 + 'A'
    for (const auto& resource : info.resources) {
        if (resource.BlockDR >= 0 && resource.BlockDR < 128 &&
            resource.BlockUR >= 0 && resource.BlockUR < 128) {
            map[resource.BlockDR][resource.BlockUR] = static_cast<char>(resource.Type + 'A');
        }
    }

    // 遍历建筑，将其块坐标标记为建筑类型 + 'a'
    for (const auto& building : info.buildings) {
        if (building.BlockDR >= 0 && building.BlockDR < 128 &&
            building.BlockUR >= 0 && building.BlockUR < 128) {
            map[building.BlockDR][building.BlockUR] = static_cast<char>(building.Type + 'a');
        }
    }

    // 遍历单位，将被单位占据的块标记为 '*'
    for (const auto& farmer : info.farmers) {
        if (farmer.BlockDR >= 0 && farmer.BlockDR < 128 &&
            farmer.BlockUR >= 0 && farmer.BlockUR < 128) {
            map[farmer.BlockDR][farmer.BlockUR] = '*';
        }
    }
    for (const auto& army : info.armies) {
        if (army.BlockDR >= 0 && army.BlockDR < 128 &&
            army.BlockUR >= 0 && army.BlockUR < 128) {
            map[army.BlockDR][army.BlockUR] = '*';
        }
    }
}

// 打印地图到文件
void printMapToFile(char map[128][128]) {
    ofstream outFile("map_debug.txt");
    if (outFile.is_open()) {
        for (int i = 0; i < 128; ++i) {
            for (int j = 0; j < 128; ++j) {
                outFile << map[i][j];
            }
            outFile << endl;
        }
        outFile.close();
    }
}

// 判断矩形区域是否为空地
bool isAreaEmpty(char map[128][128], int startDR, int startUR, int width, int height) {
    for (int i = startDR; i < startDR + width; ++i) {
        for (int j = startUR; j < startUR + height; ++j) {
            if (i < 0 || i >= 128 || j < 0 || j >= 128) return false;
            if (map[i][j] != '-' && map[i][j] < '1' && map[i][j] > '9') return false;
        }
    }
    return true;
}

// 寻找近岸渔场资源
int findNearShoreFishingGround(tagInfo& info) {
    int nearestSN = -1;
    double minDistance = 1e6;
    tagBuilding* center = nullptr;

    // 找到市镇中心
    for (const auto& building : info.buildings) {
        if (building.Type == BUILDING_CENTER) {
            center = const_cast<tagBuilding*>(&building);
            break;
        }
    }

    if (!center) return -1;

    for (const auto& resource : info.resources) {
        if (resource.Type == RESOURCE_FISH) {
            // 判断是否为近岸渔场
            bool isNearShore = false;
            for (int i = -1; i <= 1; ++i) {
                for (int j = -1; j <= 1; ++j) {
                    if (i == 0 && j == 0) continue;
                    int checkDR = resource.BlockDR + i;
                    int checkUR = resource.BlockUR + j;
                    if (checkDR >= 0 && checkDR < 128 && checkUR >= 0 && checkUR < 128) {
                        if (info.theMap[checkDR][checkUR] > 0) {
                            isNearShore = true;
                            break;
                        }
                    }
                }
                if (isNearShore) break;
            }

            if (isNearShore) {
                double distance = calDistance(center->BlockDR, center->BlockUR,
                                              resource.BlockDR, resource.BlockUR);
                if (distance < minDistance) {
                    minDistance = distance;
                    nearestSN = resource.SN;
                }
            }
        }
    }
    return nearestSN;
}

// 寻找最近的树木资源
int findNearestTree(tagInfo& info, int farmerDR, int farmerUR) {
    int nearestSN = -1;
    double minDistance = 1e6;

    for (const auto& resource : info.resources) {
        if (resource.Type == RESOURCE_TREE) {
            double distance = calDistance(farmerDR, farmerUR,
                                          resource.BlockDR, resource.BlockUR);
            if (distance < minDistance) {
                minDistance = distance;
                nearestSN = resource.SN;
            }
        }
    }
    return nearestSN;
}
pair<int, int> findDockPosition(tagInfo& info) {
    if (info.farmers.empty()) return {-1, -1};
    // 初始村民位置（取第一个村民）
    const auto& initialFarmer = info.farmers[0];
    int farmerDR = initialFarmer.BlockDR;
    int farmerUR = initialFarmer.BlockUR;
    double minDist = 1e9;
    pair<int, int> bestPos = {-1, -1};

    // 遍历地图寻找符合条件的位置（文档要求：船坞需建在海上且相邻陆地）
    for (int dr = 0; dr < 128; ++dr) {
        for (int ur = 0; ur < 128; ++ur) {
            // 检查是否为海洋（theMap值<=0）
            if (info.theMap[dr][ur] <= 0) {
                // 检查相邻地块是否有陆地（确保靠岸）
                bool adjacentToLand = false;
                for (int d = -1; d <= 1; ++d) {
                    for (int u = -1; u <= 1; ++u) {
                        if (d == 0 && u == 0) continue;
                        int checkDR = dr + d;
                        int checkUR = ur + u;
                        if (checkDR >= 0 && checkDR < 128 && checkUR >= 0 && checkUR < 128) {
                            if (info.theMap[checkDR][checkUR] > 0) {
                                adjacentToLand = true;
                                break;
                            }
                        }
                    }
                    if (adjacentToLand) break;
                }
                if (adjacentToLand) {
                    // 计算到初始村民的距离，选择最近位置
                    double dist = calDistance(dr, ur, farmerDR, farmerUR);
                    if (dist < minDist) {
                        minDist = dist;
                        bestPos = {dr, ur};
                    }
                }
            }
        }
    }
    return bestPos;
}
// 新增：按距离排序渔场（最近优先，便于分配任务）
vector<FishingSpot> getSortedFishingSpots(tagInfo& info, tagBuilding* center) {
    vector<FishingSpot> spots;
    if (!center) return spots;
    // 遍历所有渔场，计算距离并存储
    for (const auto& res : info.resources) {
        if (res.Type == RESOURCE_FISH) {
            double dist = calDistance(center->BlockDR, center->BlockUR,
                                      res.BlockDR, res.BlockUR);
            spots.push_back({res.SN, dist, res.Cnt});
        }
    }
    // 按距离升序排序
    sort(spots.begin(), spots.end(), [](const FishingSpot& a, const FishingSpot& b) {
        return a.distance < b.distance;
    });
    return spots;
}

// 更新任务状态（清除已耗尽资源的任务）
void updateTasks(tagInfo& info) {
    // 过滤村民渔场任务（保留资源未耗尽的任务）
    vector<Task> validFishingTasks;
    for (const auto& task : fishingTasks) {
        for (const auto& res : info.resources) {
            if (res.SN == task.targetSN && res.Type == RESOURCE_FISH && res.Cnt > 0) {
                validFishingTasks.push_back(task);
                break;
            }
        }
    }
    fishingTasks = validFishingTasks;

    // 过滤渔船任务（保留资源未耗尽的任务）
    vector<Task> validBoatTasks;
    for (const auto& task : boatTasks) {
        for (const auto& res : info.resources) {
            if (res.SN == task.targetSN && res.Type == RESOURCE_FISH && res.Cnt > 0) {
                validBoatTasks.push_back(task);
                break;
            }
        }
    }
    boatTasks = validBoatTasks;
}

void UsrAI::processData() {
    tagInfo info = getInfo();
    char map[128][128] = {0};

    // 建立地图
    buildMap(info, map);

    // 打印地图到文件
    printMapToFile(map);

    // 查找市镇中心
    tagBuilding* center = nullptr;
    for (const auto& building : info.buildings) {
        if (building.Type == BUILDING_CENTER) {
            center = const_cast<tagBuilding*>(&building);
            break;
        }
    }

    if (!center) return;

    // 连续生产村民
    if (center->Project == 0 && info.Meat >= 50) {
        BuildingAction(center->SN, BUILDING_CENTER_CREATEFARMER);
    }

    // 住房规划参数
    static int homeCount = 0;  // 已建造的住房数量
    static int nextHomeX = center->BlockDR + 6;  // 下一个住房的X坐标
    static int nextHomeY = center->BlockUR + 4;  // 下一个住房的Y坐标

    // 高效住房规划 - 寻找合适的建造位置
    bool homeBuilt = false;
    for (const auto& farmer : info.farmers) {
        if (farmer.NowState == HUMAN_STATE_IDLE && info.Wood >= 30 && !homeBuilt) {
            // 检查当前位置是否可以建造住房 (4x2 区域)
            if (isAreaEmpty(map, nextHomeX, nextHomeY, 4, 2)) {
                int ret = HumanBuild(farmer.SN, BUILDING_HOME, nextHomeX, nextHomeY);
                if (ret >= 0) {  // 建造命令成功发出
                    homeCount++;
                    homeBuilt = true;

                    // 规划下一个住房位置 (横向排列)
                    nextHomeX += 5;

                    // 如果横向空间不足，换行并留出农田空间
                    if (nextHomeX + 4 > 120) {
                        nextHomeX = center->BlockDR + 6;
                        nextHomeY += 6;
                    }
                }
            }
        }
    }

    // 采集资源：优先采集近岸渔场，其次砍伐树木
    bool hasFishingTask = false;
    int fishingGroundSN = findNearShoreFishingGround(info);

    for (const auto& farmer : info.farmers) {
        if (farmer.NowState == HUMAN_STATE_IDLE) {
            // 如果有近岸渔场且食物不足，优先派村民捕鱼
            if (fishingGroundSN != -1 && info.Meat < 200 && !hasFishingTask) {
                HumanAction(farmer.SN, fishingGroundSN);
                hasFishingTask = true;
            } else {
                // 否则砍伐最近的树木
                int treeSN = findNearestTree(info, farmer.BlockDR, farmer.BlockUR);
                if (treeSN != -1) {
                    HumanAction(farmer.SN, treeSN);
                }
            }
        }
    }
    //阶段1-1渔场采集任务管理（新村民优先分配最近渔场）
        updateTasks(info); // 清除无效任务（资源耗尽）
        vector<FishingSpot> sortedSpots = getSortedFishingSpots(info, center); // 按距离排序渔场

        // 为未分配任务的空闲村民分配渔场任务（优先最近渔场）
        for (const auto& farmer : info.farmers) {
            // 跳过已有任务的村民
            bool hasTask = false;
            for (const auto& task : fishingTasks) {
                if (task.unitSN == farmer.SN) {
                    hasTask = true;
                    break;
                }
            }
            if (!hasTask && farmer.NowState == HUMAN_STATE_IDLE) {
                // 每个渔场最多分配2个村民（避免拥挤）
                for (const auto& spot : sortedSpots) {
                    int assignedCount = 0;
                    for (const auto& t : fishingTasks) {
                        if (t.targetSN == spot.sn) assignedCount++;
                    }
                    if (assignedCount < 2) {
                        HumanAction(farmer.SN, spot.sn);
                        fishingTasks.push_back({farmer.SN, spot.sn, true});
                        break;
                    }
                }
            }
        }

        // 阶段1-2建造船坞（由初始村民1负责，文档表1船坞建造规则）
        if (!dockBuilt && !info.farmers.empty()) {
            const auto& initialFarmer = info.farmers[0]; // 初始村民1
            if (initialFarmer.NowState == HUMAN_STATE_IDLE) {
                auto dockPos = findDockPosition(info);
                if (dockPos.first != -1 && dockPos.second != -1 && info.Wood >= 120) { // 船坞需120木材
                    int ret = HumanBuild(initialFarmer.SN, BUILDING_DOCK, dockPos.first, dockPos.second);
                    if (ret >= 0) dockBuilt = true; // 标记船坞开始建造
                }
            }
        }

        // 阶段1-2：船坞生产渔船（至上限5艘，文档表1渔船生产规则）
        tagBuilding* dock = nullptr;
        for (const auto& building : info.buildings) {
            if (building.Type == BUILDING_DOCK && building.Percent == 100) { // 仅对建成的船坞操作
                dock = const_cast<tagBuilding*>(&building);
                break;
            }
        }
        if (dock && fishingBoatCount<=5 && info.Wood >= 60) { // 渔船需60木材
            BuildingAction(dock->SN, BUILDING_DOCK_CREATE_SAILING);
            fishingBoatCount++;
        }

        // 阶段1-2：渔船捕鱼（最近渔场，资源耗尽则探索，文档表2渔船功能）
        for (const auto& farmer : info.farmers) {
            if (farmer.FarmerSort == 2) { // 渔船（FarmerSort=2，文档4.1结构体定义）
                // 跳过已有任务的渔船
                bool hasBoatTask = false;
                for (const auto& task : boatTasks) {
                    if (task.unitSN == farmer.SN) {
                        hasBoatTask = true;
                        break;
                    }
                }
                if (!hasBoatTask && farmer.NowState == HUMAN_STATE_IDLE) {
                    // 优先分配最近的可用渔场
                    bool assigned = false;
                    for (const auto& spot : sortedSpots) {
                        if (spot.remaining > 0) {
                            HumanAction(farmer.SN, spot.sn);
                            boatTasks.push_back({farmer.SN, spot.sn, true});
                            assigned = true;
                            break;
                        }
                    }
                    // 无可用渔场时探索新区域（向UR方向移动，文档3坐标系）
                    if (!assigned) {
                        HumanMove(farmer.SN, farmer.DR + 50, farmer.UR + 50);
                    }
                }
            }
        }
}